package org.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.zip.DataFormatException;

@Component
public class RedisIdWorker 
{
	@Autowired
	RedisTemplate redisTemplate;
	
	//开始时间搓
	public static final long BEGIN_TIMESTAMP;
	static 
	{
		LocalDateTime time = LocalDateTime.of(2025,1,1,0,0,0);
		BEGIN_TIMESTAMP = time.toEpochSecond(ZoneOffset.UTC);
	}
	
	private static final String INC_KEY = "inc:";
	private static final int COUNT_BITS = 32; 
	
	public long nextId(String keyPrefix)
	{
		//1.生成时间搓
		LocalDateTime now = LocalDateTime.now();
		long nowTime = now.toEpochSecond(ZoneOffset.UTC);
		
		long timeStamp = nowTime - BEGIN_TIMESTAMP;
		
		//2.生成序列号
		//获取当前日期，精确到天
		String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
		//自增长
		long increment = redisTemplate.opsForValue().increment(INC_KEY + keyPrefix + ":" + date);
		
		//3.拼接并返回
		return timeStamp << 32 | increment;
	}

//	public static void main(String[] args) {
//		LocalDateTime time = LocalDateTime.of(2025,1,1,0,0,0);
//		long l = time.toEpochSecond(ZoneOffset.UTC);
//		System.out.println(l);
//	}
}
